﻿using Abp.Runtime.Caching;
using Castle.Core.Logging;
using System;
using System.Threading.Tasks;

namespace AbpProjectTemplate.Components.Notifications.SMS
{
    public abstract class SmsSenderBase
    {
        public ILogger Logger { get; set; }
        public ICacheManager CacheManager { get; set; }
        protected int MobileCodeExpireInMinutes { get; private set; } = 10;
        protected ITypedCache<string, string> MobileCodeCache
        {
            get { return this.CacheManager.GetCache<string, string>("SMS:MobileCode"); }
        }
        protected ITypedCache<string, string> SendCheckCache
        {
            get { return this.CacheManager.GetCache<string, string>("SMS:MobileCodeTime"); }
        }
        public SmsSenderBase()
        {
            this.Logger = NullLogger.Instance;
        }
        public async Task<bool> ValidateMobileCodeAsync(string mobile, string code)
        {
            var cachedCode = await this.MobileCodeCache.GetOrDefaultAsync(mobile);
            return cachedCode != null && cachedCode == code;
        }
        /// <summary>
        /// 发送成功以后，缓存数据
        /// </summary>
        protected virtual async Task CacheSendAsync(string mobile, string code)
        {
            await this.MobileCodeCache.SetAsync(mobile, code, new TimeSpan(0, this.MobileCodeExpireInMinutes, 0));
            await this.SendCheckCache.SetAsync(mobile, code, new TimeSpan(0, 2, 0));
        }

        /// <summary>
        /// 发送频率检查
        /// </summary>
        /// <param name="mobile"></param>
        protected virtual void SendCheck(string mobile)
        {
            // 2分钟之内发第二次，不允许发送
            if (this.SendCheckCache.GetOrDefault(mobile) != null)
                throw new AppUserFriendlyException("短信发送过于频繁！");
        }
    }
}
